import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Menu,
  Badge,
  Table,
  Modal,
  Input,
  Button,
  Divider,
  message,
  Cascader,
  Dropdown,
  Tooltip,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';
import { TableListItem } from './data';

const menuStyle = {
  padding: '3px 12px',
};

type IStatusMapType = 'success' | 'error';
const statusMap = ['error', 'success'];
const statusValues = ['禁用', '激活'];

const { Item } = Form;
const { pathname } = window.location;

interface VIPUserManagementListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
}

interface VIPUserManagementListState {
  searchValues: any;
  visible: boolean;
  record: any;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(
  ({
    VIPUserManagementList: { dataInfo },
    common: { INITINFO },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    INITINFO,
    screen,
    hasPath,
    loading: loading.effects['VIPUserManagementList/fetch'],
  }),
)
class VIPUserManagementListElem extends React.Component<VIPUserManagementListProps,
VIPUserManagementListState> {
  columns: any = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 180,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowVIP(record.id, text, record.confCount)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '联系人',
      dataIndex: 'contact',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '电话',
      dataIndex: 'phone',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (text: IStatusMapType) => <Badge
        status={statusMap[text]}
        text={statusValues[text]}
      />,
    },
    {
      title: '修改人',
      dataIndex: 'updateUserName',
      width: 100,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      width: 180,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 100,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '操作',
      width: 180,
      fixed: 'right',
      dataIndex: 'id',
      render: (text: any, record: any) => (
        <div>
          <span className="operLink" onClick={() => this.handleEditVIP(text, record.name)}>
            编辑
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleShowVIP(text, record.name, record.confCount)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={this.menu(record)} trigger={['click']}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </div>
      ),
    },
  ];

  state: VIPUserManagementListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    visible: false,
    rowId: 0,
    record: {
      id: '',
      status: 0,
    },
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const {
      pageIndex,
      pageSize,
      areaCodes,
      ...values
    } = query;
    const area = areaCodes && JSON.parse(areaCodes);
    return {
      searchValues: {
        ...values,
        areaCodes: area,
      },
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
    this.fetchAction('common/fetchAddressList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const { areaCodes = [], ...query } = searchValues;
    const params = {
      ...query,
      pageIndex,
      pageSize,
    };
    if (areaCodes.length) params.areaCode = areaCodes[areaCodes.length - 1];
    return params;
  };

  menu = (record: any) => (
    <Menu>
      <Menu.Item
        key="0"
        style={menuStyle}
        onClick={() => this.handleConfPreferential(record.id, record.name)}
      >
        <span className="operLink">配置优惠信息</span>
      </Menu.Item>
      <Menu.Item
        key="1"
        style={menuStyle}
        onClick={() => this.handleConfCompany(record.id, record.name)}
      >
        <span className="operLink">配置合作快递公司</span>
      </Menu.Item>
      <Menu.Item
        key="2"
        style={menuStyle}
        onClick={() => this.handleSwitchStatus(record)}
      >
        <span className="operLink">{record.status === 1 ? '禁用' : '激活'}</span>
      </Menu.Item>
      <Menu.Item
        key="3"
        style={menuStyle}
        onClick={() => this.handleStatistical(record.id, record.vipCode, record.name)}
      >
        <span className="operLink">统计</span>
      </Menu.Item>
    </Menu>
  );

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { areaCodes } = values;
      const query = {
        ...values,
        areaCodes: JSON.stringify(areaCodes),
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: 'VIP用户管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: 'VIP用户管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 添加VIP用户
   */
  handleAddVIP = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建VIP用户',
      url: '/basic/VIPUserManagement/list/add',
    });
  };

  /**
   * 编辑VIP用户
   */
  handleEditVIP = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/VIPUserManagement/list/edit?id=${id}`,
    });
  };

  /**
   * 查看VIP用户
   */
  handleShowVIP = (id: number, name: string, confCount: number) => {
    if (confCount <= 0) {
      message.warning('折扣信息不存在');
      return;
    }

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/basic/VIPUserManagement/list/detail?id=${id}`,
    });
  };

  /**
   * 配置优惠信息
   */
  handleConfPreferential = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `配置优惠${name}`,
      url: `/basic/VIPUserManagement/list/discount?id=${id}`,
    });
  };

  /**
   * 配置合作快递公司
   */
  handleConfCompany = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `配置公司${name}`,
      url: `/basic/VIPUserManagement/list/express?id=${id}`,
    });
  };

  /**
   * 统计
   */
  handleStatistical = (id: number, vipCode: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `配置公司${name}`,
      url: `/basic/VIPUserManagement/list/count?id=${id}&vipCode=${vipCode}`,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: 'VIP用户管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  handleSwitchStatus = (record: TableListItem) => {
    const { id } = record;
    this.setState({
      visible: true,
      record: {
        id,
        status: record.status === 1 ? 0 : 1,
      },
    });
  };

  handleConfirm = () => {
    const { record, searchValues: search } = this.state;
    record.status = record.status === '禁用' ? 0 : 1;
    const params = { ...record, search };
    this.fetchAction('changeStatus', params);
    this.handleCancel();
  };

  handleCancel = () => this.setState({ visible: false });

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `VIPUserManagementList/${typeName}`;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      pageIndex, pageSize, visible, record,
    } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { addressList },
      loading,
      screen,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="商户名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　商户ID" colon={false}>
                  {getFieldDecorator('id')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="VIP编号" colon={false}>
                  {getFieldDecorator('vipCode')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　省市区" colon={false}>
                  {getFieldDecorator('areaCodes')(
                    <Cascader changeOnSelect options={addressList} placeholder="请选择" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　联系人" colon={false}>
                  {getFieldDecorator('contact')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="手机号码" colon={false}>
                  {getFieldDecorator('phone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={12} sm={24} className="flexFeView">
                <Button
                  type="primary"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
                <Button
                  type="primary"
                  className="addButton smallButton marginL16"
                  onClick={this.handleReset}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddVIP}
            >
              新建VIP用户
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
          <Modal
            title="确认提示"
            visible={visible}
            onOk={this.handleConfirm}
            onCancel={this.handleCancel}
          >
            <p style={{ textAlign: 'center' }}>
              您确定要{record.status === 0 ? '禁用' : '激活'}此快递公司吗？
            </p>
          </Modal>
        </Card>
      </>
    );
  }
}

export default Form.create<VIPUserManagementListProps>()(VIPUserManagementListElem);
